package edu.tgc.service.qrtz;

import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;

import edu.tgc.entity.qrtz.QrtzJob;

public class QrtzJobService {

    protected SchedulerFactory schedulerFactory;

    // 增加job
    @SuppressWarnings("unchecked")
    public void createJob(QrtzJob qrtzJob) {
        try {
            Scheduler scheduler = this.schedulerFactory.getScheduler();
            JobKey jobKey = qrtzJob.getJobKey();
            JobDetail jobDetail = JobBuilder.newJob((Class<Job>) Class.forName(qrtzJob.getClassName())).withIdentity(jobKey).withDescription(qrtzJob.getDescription()).requestRecovery(qrtzJob.getRecovery()).storeDurably(qrtzJob.getDurable()).build();
            scheduler.addJob(jobDetail, true, !qrtzJob.getDurable());
        } catch (SchedulerException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    // 删除job
    public void deleteJob(QrtzJob qrtzJob) {
        try {
            Scheduler scheduler = this.schedulerFactory.getScheduler();
            JobKey jobKey = qrtzJob.getJobKey();
            if (scheduler.checkExists(jobKey)) {
                scheduler.deleteJob(jobKey);
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

}
